package services

import (
	"context"
	"encoding/base64"
	"gitee.com/brookscoder/awesome-mall-go/common"
	"gitee.com/brookscoder/awesome-mall-go/dao/redis"
	"gitee.com/brookscoder/awesome-mall-go/dao/sqlx"
	"gitee.com/brookscoder/awesome-mall-go/model"
)

func Login(ctx context.Context, req model.LoginRequest) (interface{}, error) {
	// 加密用户输入的密码
	strbytes := []byte(req.Password)
	encodedPasswd := base64.StdEncoding.EncodeToString(strbytes)

	dbu := sqlx.QueryUserInfo(req.PhoneNumber)
	if 0 == dbu.Id {
		return nil, common.ErrQueryUser
	} else if encodedPasswd != dbu.Password {
		return nil, common.ErrWrongPasswd
	}

	return dbu, nil
}

func Register(c context.Context, req model.RegisterRequest) (interface{}, error) {
	// 校验验证码
	smsCode, err := redis.ReadChptcha(req.PhoneNumber)
	if err != nil {
		return nil, common.ErrWrongCode
	}
	if req.SMSCode != smsCode {
		return nil, common.ErrWrongCode
	}

	// 加密用户输入的密码
	strbytes := []byte(req.Password)
	encodedPasswd := base64.StdEncoding.EncodeToString(strbytes)

	r := sqlx.AddUserInfo(req.PhoneNumber, encodedPasswd)
	if r == false {
		return nil, common.ErrAddUser
	} else {
		return true, nil
	}
}
